package com.kds.fxtool.controller;

import com.kds.fxtool.config.ResourceManager;
import com.kds.fxtool.config.SceneManager;
import com.kds.fxtool.service.CaptchaService;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.animation.ScaleTransition;
import javafx.scene.image.ImageView;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.Duration;

import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;

import static com.kds.fxtool.service.CaptchaService.validateCaptcha;

public class LoginController implements Initializable {

    @FXML private TextField usernameField;
    @FXML private PasswordField passwordField;
    @FXML private TextField captchaField;
    @FXML private Label messageLabel;
    @FXML private Button loginButton;
    @FXML private CheckBox rememberCheckBox;
    @FXML private ImageView captchaImageView;
    @FXML private Label loginMethodLabel;
    @FXML private VBox accountLoginArea;
    @FXML private VBox wechatLoginArea;
    @FXML private Label qrcodeStatusLabel;
    @FXML private ProgressIndicator qrcodeProgress;

    // 当前验证码ID
    private String currentCaptchaId;
    private boolean isWechatLoginMode = false;
    private Thread qrcodePollingThread;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        setupEnterKeyHandler();
        setupButtonAnimations();
        // 初始化时生成验证码
        refreshCaptcha();

        // 设置登录方式切换标签的鼠标事件
        setupLoginMethodSwitcher();
    }

    /**
     * 切换登录方式
     */
    @FXML
    private void switchLoginMethod() {
        isWechatLoginMode = !isWechatLoginMode;

        if (isWechatLoginMode) {
            // 切换到微信登录
            switchToWechatLogin();
        } else {
            // 切换到账号密码登录
            switchToAccountLogin();
        }

        // 添加切换动画
        animateLoginMethodSwitch();
    }

    /**
     * 切换到微信登录
     */
    private void switchToWechatLogin() {
        loginMethodLabel.setText("账号密码登录 →");
        accountLoginArea.setVisible(false);
        accountLoginArea.setManaged(false);
        wechatLoginArea.setVisible(true);
        wechatLoginArea.setManaged(true);

        // 开始微信二维码轮询
        startQrcodePolling();
    }

    /**
     * 切换到账号密码登录
     */
    private void switchToAccountLogin() {
        loginMethodLabel.setText("微信扫码登录 →");
        wechatLoginArea.setVisible(false);
        wechatLoginArea.setManaged(false);
        accountLoginArea.setVisible(true);
        accountLoginArea.setManaged(true);

        // 停止微信二维码轮询
        stopQrcodePolling();
    }

    /**
     * 开始微信二维码轮询
     */
    private void startQrcodePolling() {
        qrcodeStatusLabel.setText("正在生成二维码...");
        qrcodeProgress.setVisible(true);

        // 模拟生成二维码和轮询过程
        qrcodePollingThread = new Thread(() -> {
            try {
                // 模拟生成二维码的延迟
                Thread.sleep(1500);

                javafx.application.Platform.runLater(() -> {
                    qrcodeStatusLabel.setText("等待扫描...");
                });

                // 模拟轮询过程
                for (int i = 0; i < 30; i++) {
                    if (Thread.currentThread().isInterrupted()) {
                        break;
                    }

                    Thread.sleep(2000);

                    // 这里可以添加实际的微信登录状态检查
                    // 如果检测到用户已扫码并确认登录，则自动登录

                    int finalI = i;
                    javafx.application.Platform.runLater(() -> {
                        // 模拟不同的状态
                        if (finalI == 5) {
                            qrcodeStatusLabel.setText("二维码已扫描");
                        } else if (finalI == 8) {
                            qrcodeStatusLabel.setText("登录确认中...");
                        } else if (finalI == 10) {
                            qrcodeStatusLabel.setText("登录成功!");
                            qrcodeProgress.setVisible(false);
                            handleWechatLoginSuccess();
                        }
                    });

                    if (i == 10) break;
                }

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });

        qrcodePollingThread.start();
    }

    /**
     * 停止微信二维码轮询
     */
    private void stopQrcodePolling() {
        if (qrcodePollingThread != null && qrcodePollingThread.isAlive()) {
            qrcodePollingThread.interrupt();
        }
        qrcodeProgress.setVisible(false);
    }

    /**
     * 微信登录成功处理
     */
    private void handleWechatLoginSuccess() {
        showMessage("微信登录成功! 正在进入系统...", "success");

        // 模拟跳转
        new Thread(() -> {
            try {
                Thread.sleep(2000);
                javafx.application.Platform.runLater(() -> {
                    // 跳转到主界面
                    showMessage("正在跳转到主界面...", "success");
                    SceneManager.switchToMain();
                });
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
    }

    /**
     * 设置登录方式切换标签的交互
     */
    private void setupLoginMethodSwitcher() {
        loginMethodLabel.hoverProperty().addListener((obs, oldVal, newVal) -> {
            ScaleTransition st = new ScaleTransition(Duration.millis(150), loginMethodLabel);
            st.setToX(newVal ? 1.05 : 1.0);
            st.setToY(newVal ? 1.05 : 1.0);
            st.play();
        });
    }

    /**
     * 登录方式切换动画
     */
    private void animateLoginMethodSwitch() {
        ScaleTransition st = new ScaleTransition(Duration.millis(200), loginMethodLabel);
        st.setToX(0.95);
        st.setToY(0.95);
        st.setAutoReverse(true);
        st.setCycleCount(2);
        st.play();
    }


    private void setupEnterKeyHandler() {
        usernameField.setOnAction(event -> handleLogin());
        passwordField.setOnAction(event -> handleLogin());
        captchaField.setOnAction(event -> handleLogin());
    }

    private void setupButtonAnimations() {
        // 登录按钮动画
        loginButton.hoverProperty().addListener((obs, oldVal, newVal) -> {
            animateScale(loginButton, newVal ? 1.02 : 1.0);
        });
    }

    private void animateScale(Control control, double scale) {
        ScaleTransition st = new ScaleTransition(Duration.millis(200), control);
        st.setToX(scale);
        st.setToY(scale);
        st.play();
    }

    /**
     * 刷新验证码
     */
    @FXML
    private void handleRefreshCaptcha() {
        refreshCaptchaWithAnimation();
    }

    /**
     * 生成新验证码并显示（带动画效果）
     */
    private void refreshCaptchaWithAnimation() {
        // 先执行缩小动画
        ScaleTransition shrink = new ScaleTransition(Duration.millis(150), captchaImageView);
        shrink.setToX(0.8);
        shrink.setToY(0.8);

        shrink.setOnFinished(event -> {
            // 生成新验证码
            refreshCaptcha();

            // 执行恢复动画
            ScaleTransition grow = new ScaleTransition(Duration.millis(150), captchaImageView);
            grow.setToX(1.0);
            grow.setToY(1.0);
            grow.play();
        });

        shrink.play();
    }

    /**
     * 生成新验证码并显示
     */
    private void refreshCaptcha() {
        try {
            // 生成图形验证码
            CaptchaService.CaptchaResult captchaResult = CaptchaService.generateImageCaptcha();

            // 更新验证码图片
            captchaImageView.setImage(captchaResult.getImage());

            // 保存验证码ID
            currentCaptchaId = captchaResult.getCaptchaId();

            // 清空验证码输入框
            captchaField.clear();

            // 可选：在控制台输出验证码答案（用于调试）
            System.out.println("验证码答案: " + captchaResult.getAnswer());

        } catch (Exception e) {
            showMessage("验证码生成失败，请重试", "error");
            e.printStackTrace();
        }
    }

    @FXML
    private void handleLogin() {
        String username = usernameField.getText().trim();
        String password = passwordField.getText();
        String captcha = captchaField.getText().trim();

        animateButton(loginButton);

        if (username.isEmpty() || password.isEmpty()) {
            showMessage("用户名和密码不能为空!", "error");
            return;
        }

        if (captcha.isEmpty()) {
            showMessage("请输入验证码!", "error");
            return;
        }

        // 验证验证码
//        if (!validateCaptcha(captcha)) {
//            showMessage("验证码错误，请重新输入!", "error");
//            refreshCaptcha(); // 验证失败时刷新验证码
//            return;
//        }

        // 模拟登录验证
        if (validateCredentials(username, password)) {
            showMessage("登录成功! 正在进入系统...", "success");

            if (rememberCheckBox.isSelected()) {
                saveLoginInfo(username);
            }

            // 模拟跳转
            simulateNavigation();
        } else {
            showMessage("用户名或密码错误!", "error");
            refreshCaptcha(); // 登录失败时刷新验证码
        }
    }

    /**
     * 验证验证码
     */
    private boolean validateCaptcha(String userInput) {
        if (currentCaptchaId == null) {
            return false;
        }

        boolean isValid = CaptchaService.validateCaptcha(currentCaptchaId, userInput);

        if (!isValid) {
            // 验证失败时清除当前验证码ID
            currentCaptchaId = null;
        }

        return isValid;
    }

    @FXML
    private void handleGetCaptcha() {
        showMessage("验证码已发送到您的手机", "info");
        // 这里添加获取验证码的逻辑
    }

    @FXML
    private void handleForgotPassword() {
        showMessage("密码重置链接已发送到您的邮箱", "info");
    }

    @FXML
    private void handleRegister() {
        showMessage("正在跳转到注册页面...", "info");
    }

    @FXML
    private void handleWechatLogin() {
        showMessage("正在生成微信二维码...", "info");

        // 模拟微信扫码登录流程
        new Thread(() -> {
            try {
                // 模拟生成二维码的延迟
                Thread.sleep(1000);

                javafx.application.Platform.runLater(() -> {
                    showMessage("请使用微信扫描二维码登录", "info");

                    // 这里可以添加实际的微信扫码登录逻辑
                    // 比如显示二维码图片、轮询登录状态等
                });

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }).start();
    }

    @FXML
    private void handleQQLogin() {
        showMessage("正在通过QQ登录...", "info");
    }

    @FXML
    private void handleDingTalkLogin() {
        showMessage("正在通过钉钉登录...", "info");
    }

    @FXML
    private void handleMinimize() {
        SceneManager.minimizeWindow();
    }

    @FXML
    private void handleClose() {
        SceneManager.closeWindow();
    }

    private boolean validateCredentials(String username, String password) {
        // 模拟验证逻辑
        return "admin".equals(username) && "123456".equals(password);
    }

    private void showMessage(String message, String type) {
        messageLabel.setText(message);
        messageLabel.getStyleClass().removeAll("success-message", "error-message", "info-message");

        switch (type) {
            case "error":
                messageLabel.getStyleClass().add("error-message");
                break;
            case "success":
                messageLabel.getStyleClass().add("success-message");
                break;
            case "info":
                messageLabel.getStyleClass().add("info-message");
                break;
        }
    }

    private void saveLoginInfo(String username) {
        // 保存登录信息逻辑
        System.out.println("保存用户信息: " + username);
    }

    private void simulateNavigation() {
        try {
            showMessage("登录成功! 正在进入系统...", "success");

            // 延迟跳转，让用户看到成功消息
            new Thread(() -> {
                try {
                    Thread.sleep(1000); // 等待1秒让用户看到成功消息

                    javafx.application.Platform.runLater(() -> {
                        try {
                            // 获取当前舞台
                            Stage currentStage = (Stage) usernameField.getScene().getWindow();

                            // 使用 SceneManager 切换到主页面
                            SceneManager.switchToMain();

                            // 不需要关闭当前窗口，SceneManager 会处理场景切换

                        } catch (Exception e) {
                            e.printStackTrace();
                            showMessage("加载主界面失败: " + e.getMessage(), "error");
                        }
                    });

                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }).start();
        } catch (Exception e) {
            e.printStackTrace();
            showMessage("跳转失败: " + e.getMessage(), "error");
        }
    }

    private void animateButton(Button button) {
        ScaleTransition st = new ScaleTransition(Duration.millis(100), button);
        st.setToX(0.95);
        st.setToY(0.95);
        st.setAutoReverse(true);
        st.setCycleCount(2);
        st.play();
    }

    /**
     * 设置验证码图片的交互
     */
    private void setupCaptchaImage() {
        // 鼠标悬停效果
        captchaImageView.hoverProperty().addListener((obs, oldVal, newVal) -> {
            if (newVal) {
                captchaImageView.setStyle("-fx-border-color: #667eea; -fx-effect: dropshadow(one-pass-box, rgba(102,126,234,0.2), 3, 0, 0, 2);");
            } else {
                captchaImageView.setStyle("-fx-border-color: #e1e8ed; -fx-effect: dropshadow(one-pass-box, rgba(0,0,0,0.1), 2, 0, 0, 1);");
            }
        });
    }
}